#include "spiffsTest.h"
#include "MySpiffs.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "cmd/cmd.h"
#include "esp_log.h"

extern CmdHandle_t CmdHandle;
extern TaskHandle_t testSpiffshand;

const char* teatdata1 = "this is data1";
const char* teatPath1 = "/spiffs/data1.txt";

const char* teatdata2 = "this is data2";
const char* teatPath2 = "/spiffs/data2.txt";

const char* teatdata3 = "this is data3";
const char* teatPath3 = "/spiffs/data3.txt";

static const char *TAG = "spiffsTestTag";

static const char *basepath = "/spiffs/";

PathArray path_array;

void actionSpiffs(void* n)
{
	init_spiffs();
}

void actionSpiffsWrite1(void* n)
{
    write_file(teatPath1, teatdata1) ;

}

void actionSpiffsRead1(void* n)
{
    read_file(teatPath1) ;
}

void actionSpiffsWrite2(void* n)
{
    write_file(teatPath2, teatdata2) ;

}

void actionSpiffsRead2(void* n)
{
    read_file(teatPath2) ;
}

void actionSpiffsWrite3(void* n)
{
    write_file(teatPath3, teatdata3) ;

}

void actionSpiffsRead3(void* n)
{
    read_file(teatPath3) ;
}

void getShowAllPath(void* n)
{
    ESP_LOGI(TAG,"Show all fail path");
    // list_with_nftw() ;
    list_spiffs_directory("/spiffs");
}

void actionWriteData(void* n)
{
    ESP_LOGI(TAG,"into write action");
    char path[256];
    snprintf(path, sizeof(path), "%s%s", basepath, (char*)n);
    char data[512];
    snprintf(data, sizeof(data), "data save path is:%s", path);
    write_file(path, data) ;
}

void actionReadAllPath(void* n)
{
    store_paths_recursive(&path_array, "/spiffs");
    
    // 使用路径数组
    ESP_LOGI(TAG,"find %d path:\n", path_array.count);
    for (int i = 0; i < path_array.count; i++) 
    {
        ESP_LOGI(TAG,"%d: %s\n", i, path_array.paths[i]);
    }
}

void actionDeleteAll(void* n)
{
    store_paths_recursive(&path_array, "/spiffs");
    
    for (int i = 0; i < path_array.count; i++) 
    {
        delete_file(path_array.paths[i]) ;
    }
}

void test_spiffs_task(void *pvParameters) 
{
    init_path_array(&path_array, 10); // 初始容量10

    MyCMDRegisterIns(&CmdHandle, InsAction, "initspiffs", actionSpiffs);

    MyCMDRegisterIns(&CmdHandle, InsAction, "write1", actionSpiffsWrite1);
    MyCMDRegisterIns(&CmdHandle, InsAction, "read1", actionSpiffsRead1);

    MyCMDRegisterIns(&CmdHandle, InsAction, "write2", actionSpiffsWrite2);
    MyCMDRegisterIns(&CmdHandle, InsAction, "read2", actionSpiffsRead2);

    MyCMDRegisterIns(&CmdHandle, InsAction, "write3", actionSpiffsWrite3);
    MyCMDRegisterIns(&CmdHandle, InsAction, "read3", actionSpiffsRead3);

    MyCMDRegisterIns(&CmdHandle, InsGet, "showpath", getShowAllPath);

    MyCMDRegisterIns(&CmdHandle, InsAction, "savedata", actionWriteData);
    MyCMDRegisterIns(&CmdHandle, InsAction, "readall", actionReadAllPath);

    MyCMDRegisterIns(&CmdHandle, InsAction, "deleteall", actionDeleteAll);

    vTaskDelete(testSpiffshand);
}